package net.zhengxinyun.performance.controller.workSupervision;

import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.dto.ExcelDTO;
import net.zhengxinyun.performance.entity.TokenEntity;
import net.zhengxinyun.performance.entity.WorkSupervisionEntity;
import net.zhengxinyun.performance.filter.WorkSupervisionFilter;
import net.zhengxinyun.performance.service.exportService.ExcelDtoService;
import net.zhengxinyun.performance.service.login.TokenService;
import net.zhengxinyun.performance.service.workSupervision.WorkSupervisionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 专项工作督查 指标管理
 */
@RestController
@RequestMapping("/workSupervision")
public class WorkSupervisionController {

    private TokenService tokenService;
    private WorkSupervisionService workSupervisionService;

    @Autowired
    private ExcelDtoService excelDtoService;

    @Autowired
    public WorkSupervisionController(TokenService tokenService, WorkSupervisionService workSupervisionService) {
        this.tokenService = tokenService;
        this.workSupervisionService = workSupervisionService;
    }

    @GetMapping(value = "/file")
    public String file() {
        return "file";
    }

    @PostMapping("/insert")
    public Result<String> insert(@RequestBody WorkParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            param.workSupervisionEntity.setAudit("1");
            List<String> cooperateUnits = param.workSupervisionEntity.getCooperateUnits();
            String strCoo = String.join(",",cooperateUnits);

            List<String> leaderId = param.workSupervisionEntity.getLeaderId();
            if(ObjectUtils.isNotBlank(leaderId))
            {
                String leaderName = String.join(",",leaderId);

                param.workSupervisionEntity.setLeaderName(leaderName);

            }
            param.workSupervisionEntity.setId(null);
            param.workSupervisionEntity.setCooperateUnit( strCoo);
            String str = workSupervisionService.insert(param.workSupervisionEntity);
            if (!"添加成功".equals(str)) {
                return ResultUtils.getResults(Result.Status.ERROR, str);
            }
            return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    @PostMapping("/update")
    public Result<String> update(@RequestBody WorkParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            if(ObjectUtils.isBlank(param.workSupervisionEntity.getId()))
            {
                return   ResultUtils.getResults(Result.Status.ERROR, "主键ID空值，请刷新页面");
            }
            List<String> leaderId = param.workSupervisionEntity.getLeaderId();
            if(ObjectUtils.isNotBlank(leaderId))
            {
                String leaderName = String.join(",",leaderId);

                param.workSupervisionEntity.setLeaderName(leaderName);

            }else {
                param.workSupervisionEntity.setLeaderName(null);
            }

            String str = workSupervisionService.update(param.workSupervisionEntity);
            if (!"修改成功".equals(str)) {
                return ResultUtils.getResults(Result.Status.ERROR, str);
            }
            return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    @PostMapping("/delete")
    public Result<String> delete(@RequestBody WorkParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            String str = workSupervisionService.delete(param.workSupervisionEntity);
            if (!"删除成功".equals(str)) {
                return ResultUtils.getResults(Result.Status.ERROR, str);
            }
            return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    @PostMapping("/query")
    public Result<HashMap<String, Object>> query(@RequestBody WorkParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            List<WorkSupervisionFilter> list = workSupervisionService.query(param.workSupervisionFilter);
            if (list.size() == 0){
                param.workSupervisionFilter.setPageNumber(param.workSupervisionFilter.getPageNumber()-1);
                list = workSupervisionService.query(param.workSupervisionFilter);
            }
            Double pageTotal = Util.intGetTotalPage(workSupervisionService.queryForCount(param.workSupervisionFilter), param.workSupervisionFilter.getPageSize());
            HashMap<String, Object> map = new HashMap<>();
            for (WorkSupervisionFilter item : list) {
                item.setCooperateUnits( Util.strToList(item.getCooperateUnit()) );
                item.setLeaderId(Util.strToList(item.getLeaderName()));
            }

            map.put("list", list);


            map.put("pageTotal", pageTotal);
            return ResultUtils.getSuccessResults(map);
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }

    @RequestMapping("/setPoint")
    public Result<String> setPoint(@RequestBody WorkParam param){
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            String str = workSupervisionService.setPoint(param.workSupervisionEntity);
            if (!"设置分数成功".equals(str)){
                return ResultUtils.getResults(Result.Status.ERROR,str);
            }
            return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }
    //  导入数据
    @PostMapping("/importData")
    public Result<String> importData(@RequestParam(value = "file") MultipartFile file) {
        String str = workSupervisionService.importData(file);
        if (!"导入成功".equals(str)){
            return ResultUtils.getResults(Result.Status.ERROR,str);
        }
        return ResultUtils.getSuccessResults();
    }

    // 导入指标；
    @PostMapping("/importPoint")
    public Result<HashMap<String,Object>> importPoint(@RequestParam(value = "file") MultipartFile file) {

        if(file ==null)
        {
            return ResultUtils.getResults(Result.Status.ERROR, "上传失败，上传文件不能为空", null);
        }
        String fileName = file.getOriginalFilename();

        if(!fileName.matches("^.+\\.(?i)(xls)$")&&!fileName.matches("^.+\\.(?i)(xlsx)$")){
            return ResultUtils.getResults(Result.Status.ERROR, "上传失败，文件格式错误",null);
        }

        HashMap<String, Object> map = workSupervisionService.importPoint(file);
       int code =(int) map.get("code");

        if (code ==500){

            return ResultUtils.getResults(Result.Status.ERROR,"导入失败",null);
        }
        return ResultUtils.getSuccessResults(map);
    }

    //确认保存
    @PostMapping("/saveWorkIndex")
    public Result<String> saveWordIndexs(@RequestBody WorkParam param){
        String batchNum = param.excelDTO.getBatchNum();
        if(StringUtils.isBlank(batchNum))
        {
            return  ResultUtils.getResults(Result.Status.ERROR,"批次号为空，请重新操作");
        }

        List<ExcelDTO> excelDTOS = excelDtoService.queryData(batchNum, 1);

        int i = workSupervisionService.batchSaveWorkIndexs(excelDTOS);
        if(i==0)
        {
            return ResultUtils.getSuccessResults("无数据");
        }

        return ResultUtils.getSuccessResults();

    }

    //导入后的查询
    //导入数据校验后的查询
    @PostMapping("/queryImportDTO")
    public Result<HashMap<String, Object>> queryData(@RequestBody WorkParam param )
    {

        if(ObjectUtils.isBlank(param.excelDTO))
        {
            return ResultUtils.getResults(Result.Status.ERROR, "KeyOne为空", null);
        }
        String batchNum = param.excelDTO.getBatchNum();

        if(net.zhengxinyun.performance.Util.StringUtils.isBlank(batchNum))
        {
            return ResultUtils.getResults(Result.Status.ERROR, "导入批次号为空", null);
        }

        List<ExcelDTO> dtoList = excelDtoService.queryData(batchNum,null);
        List<ExcelDTO> collect = dtoList.stream().filter(dto -> 0==dto.getAvail()).collect(Collectors.toList());
        HashMap<String,Object> map = new HashMap<>();
        map.put("list",dtoList);
        if (collect.size()>0){
            map.put("warn","当前数据有"+collect.size()+"条警告信息。");
        }else {
            map.put("warn","校验通过，无警告数据，可直接上传数据");
        }
        return ResultUtils.getSuccessResults(map);
    }
    // 手动修改
    @PostMapping("/updateExcelDto")
    public Result<String> updateExcelDto(@RequestBody WorkParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            ExcelDTO excelDTO = param.excelDTO;
            excelDTO.setAvail(1);
            excelDTO.setRemark("");
            excelDtoService.updateExcelData(excelDTO);
            return ResultUtils.getSuccessResults();
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "token不对", null);
    }
}

class WorkParam {
    public TokenEntity tokenEntity;
    public WorkSupervisionEntity workSupervisionEntity;
    public WorkSupervisionFilter workSupervisionFilter;
    public ExcelDTO excelDTO;
}
